const express = require('express');
const router = express.Router();
const productModule=require('../database/module/productModule');
//添加商品
router.all('/addProduct',(req,res)=>{
    const data=req.body;
    const pro= new productModule({
            //product_id:new Date(),
            mvo_id: data.mvo_id,
            name:data.name,
            price:data.price,
            description:data.description,
            category:data.category,
            image_url:data.image_url,
            stock:data.stock,
            rating:data.rating,
            valid:true
    })
    pro.save().then((result)=>{
        res.send(result._id);
    });
    /* productModule.create(pro).then((result)=>{
        console.log('pro_id:',result.product_id);
        res.send(result.product_id);
     })*/
   
    
})
//删除商品
router.all('/deleteProduct',(req,res)=>{
    const data=req.body;
    productModule.updateOne({_id:data.product_id},{valid:'false'}).then((result)=>{
        //console.log(result)
        res.send(true);
    }).catch(err=>{
        res.send(false);
    })
})

//修改商品信息
router.all('/editProduct',(req,res)=>{
    const data=req.body;
    productModule.updateOne({_id:data.product_id},{   
            name:data.name,
            price:data.price,
            description:data.description,
            category:data.category,
            image_url:data.image_url,
            stock:data.stock,
            rating:data.rating
        }) .then(()=>{
            res.send(true);
        }).catch(err=>{
            res.send(err);
        }) 
})
//查看品牌商旗下的所有商品
router.all('/findAllBrandProduct',(req,res)=>{
    const data=req.body;
    productModule.find({mov_id:data.mov_id}).then(result=>{
        result = result.filter(p => p.valid===true);
        let ret = [];
        result.forEach(p => {
            const obj = {
                product_id: p._id,
                name:p.name,
                price:p.price,
                description:p.description,
                category:p.category,
                image_url:p.image_url,
                stock:p.stock,
                rating:p.rating
            }
            ret.push(obj)
        });
        res.send(ret);
    }).catch(err=>{
        console.log(err);
    })
})
//预览所有商品
router.all('/findAllProduct',(req,res)=>{
    productModule.find({valid:'true'}).then(result=>{
        result = result.filter(p => p.valid===true);
        let ret = [];
        result.forEach(p => {
            const obj = {
                product_id: p._id,
                name:p.name,
                price:p.price,
                description:p.description,
                category:p.category,
                image_url:p.image_url,
                stock:p.stock,
                rating:p.rating
            }
            ret.push(obj)
        });
        res.send(ret);
    }).catch(err=>{
        console.log(err);
    })
})


module.exports = router;